﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MOJsdk;
using System.Collections.ObjectModel;

namespace MojMovieDetails
{
    /// <summary>
    /// Interaction logic for MovieDetails.xaml
    /// </summary>
    public partial class MovieDetails : UserControl, IMetaData
    {
        private bool IsSelectIndexVisible = false;
        private string _movieCode;
        private MojMovie _movie;

        private ObservableCollection<MojMovieFile> _movieFiles;
        private ObservableCollection<MojSubtitleFile> _subFiles;

        public MovieDetails()
        {
            InitializeComponent();
            INIStyle();
            INIEvents();
        }

        private void INIStyle()
        {
            _Grid.ApplyStyle(BuildName("BackgroundGrid"));
            _tabControl.ApplyStyle(BuildName("TabControl"));

            _tabDetails.Header = MOJLocalization.Localize("Details");
            _tabFiles.Header = MOJLocalization.Localize("Files");
            _tabImages.Header = MOJLocalization.Localize("Images");
            _tabSubtitles.Header = MOJLocalization.Localize("Subtitles");

            #region DetailsTab
            _lbl_details_cast.Content = MOJLocalization.Localize("Cast") + ": ";
            _lbl_details_cast.ApplyStyle(BuildName("Details_Cast_Label"));
            _lbl_details_director.Content = MOJLocalization.Localize("Director") + ": ";
            _lbl_details_director.ApplyStyle(BuildName("Details_Director_Label"));
            _lbl_details_genre.Content = MOJLocalization.Localize("Genres") + ": ";
            _lbl_details_genre.ApplyStyle(BuildName("Details_Genre_Label"));
            _lbl_details_origin.Content = MOJLocalization.Localize("Original") + ": ";
            _lbl_details_origin.ApplyStyle(BuildName("Details_TitleOriginal_Label"));
            _lbl_details_tagline.Content = MOJLocalization.Localize("Tagline") + ": ";
            _lbl_details_tagline.ApplyStyle(BuildName("Details_TagLine_Label"));
            _lbl_details_title.Content = MOJLocalization.Localize("Title") + ": ";
            _lbl_details_title.ApplyStyle(BuildName("Details_Title_Label"));
            _lbl_details_writer.Content = MOJLocalization.Localize("Writers") + ": ";
            _lbl_details_writer.ApplyStyle(BuildName("Details_Writer_Label"));
            _lbl_details_year.Content = MOJLocalization.Localize("Year") + ": ";
            _lbl_details_year.ApplyStyle(BuildName("Details_Year_Label"));
            _txt_details_director.ApplyStyle(BuildName("Details_Director_TextBox"));
            _txt_details_origin.ApplyStyle(BuildName("Details_Origin_TextBox"));
            _txt_details_tagline.ApplyStyle(BuildName("Details_Tagline_TextBox"));
            _txt_details_title.ApplyStyle(BuildName("Details_Title_TextBox"));
            _txt_details_writer.ApplyStyle(BuildName("Details_Writer_TextBox"));
            _txt_details_year.ApplyStyle(BuildName("Details_Year_TextBox"));
            _listBox_details_cast.ApplyStyle(BuildName("Details_Cast_ListBox"));
            _listBox_details_genres.ApplyStyle(BuildName("Details_Cast_ListBox"));
            #endregion
            #region MovieFilesTab
            _btn_files_remove.IsEnabled = false;
            _btn_files_fileIndex.IsEnabled = false;

            _listView_Files.ApplyStyle(BuildName("MovieFiles_ListView"));
            _btn_files_add.Content = MOJLocalization.Localize("Add");
            _btn_files_add.ApplyStyle(BuildName("MovieFiles_Button_Add"));

            _btn_files_fileIndex.ApplyStyle(BuildName("MovieFiles_Button_Index"));

            _btn_files_remove.Content = MOJLocalization.Localize("Remove");
            _btn_files_remove.ApplyStyle(BuildName("MovieFiles_Button_Remove"));

            _lbl_files_movieOriginalName.Content = MOJLocalization.Localize("Release") + ": ";
            _lbl_files_movieOriginalName.ApplyStyle(BuildName("MovieFiles_Label_Release"));
            _lbl_files_moviePath.Content = MOJLocalization.Localize("Path") + ": ";
            _lbl_files_moviePath.ApplyStyle(BuildName("MovieFiles_Label_Path"));

            _txtBox_files_movieOriginalName.ApplyStyle(BuildName("MovieFiles_TextBox_Release"));
            _txtBox_files_moviePath.ApplyStyle(BuildName("MovieFiles_TextBox_Path"));
            #endregion
            #region SubtitlesTab
            _btn_subs_remove.IsEnabled = false;
            _btn_subs_language.IsEnabled = false;
            _btn_subs_fileIndex.IsEnabled = false;

            _listView_subtitles.ApplyStyle(BuildName("Subs_ListView"));
            _btn_subs_add.Content = MOJLocalization.Localize("Add");
            _btn_subs_add.ApplyStyle(BuildName("Subs_Button_Add"));

            _btn_subs_fileIndex.ApplyStyle(BuildName("Subs_Button_Index"));
            _btn_subs_language.ApplyStyle(BuildName("Subs_Button_Language"));

            _btn_subs_remove.Content = MOJLocalization.Localize("Remove");
            _btn_subs_remove.ApplyStyle(BuildName("Subs_Button_Remove"));

            _lbl_subs_moviePath.Content = MOJLocalization.Localize("Path") + ": ";
            _lbl_subs_moviePath.ApplyStyle(BuildName("Subs_Label_Path"));
            _txtBox_subs_moviePath.ApplyStyle(BuildName("Subs_TextBox_Path"));
            #endregion
            #region ImageTab
            _btn_imgs_selectCover.Content = MOJLocalization.Localize("Select Cover");
            _btn_imgs_selectBackdrop.Content = MOJLocalization.Localize("Select Backdrop");

            _btn_imgs_selectBackdrop.ApplyStyle(BuildName("Images_Button_SelectBackdrop"));
            _btn_imgs_selectCover.ApplyStyle(BuildName("Images_Button_SelectCover"));
            #endregion
        }
        private void INIEvents()
        {
            OnMovieInfoUpdated += delegate { };

            foreach (var elem in _Grid_Details.Children)
                if (elem.GetType() == typeof(TextBox))
                    ((TextBox)elem).LostFocus += checkText;

            _btn_subs_fileIndex.Click += SelectSubtitleIndex;
            _btn_subs_language.Click += SelectSubtitleLanguage;

            _listView_Files.SelectionChanged += OnListViewMoviesSelectionChanged;
            _btn_files_fileIndex.Click += SelectMovieIndex;
            _btn_files_remove.Click += RemoveSelectedMovieFile;
            _btn_files_add.Click += AddNewMovieFile;
        }
        #region IMetaDataMethods
        public string Identifier { get { return "MojMetaData"; } }
        public UserControl Control 
        { 
            get 
            {
                ReleaseParent();
                return this; 
            } 
        }
        public string LoadedMovie { get { return _movieCode; } }

        public double Width { get { return 600; } }
        public double Height { get { return 400; } }

        public void LoadMovie(string MovieCode) 
        {
            _movieCode = MovieCode;
            ReloadMovie();
        }
        public void ReloadMovie()
        {
            if (MojHost.GetHost.MoJSystem.MoviesInterop.MovieExist(_movieCode))
                _movie = new MojMovie(_movieCode);
            else
                _movie = null;

            FillDetails();
            FillMovies();
            FillSubtitles();
            FillImages();
        }
        public void Save()
        {
            if(_movie == null) return;

            #region DetailsUpdate
            _movie.MovieCast = _listBox_details_cast.Items.Cast<string>().ToString(";");
            _movie.MovieDirectors = _txt_details_director.Text;
            _movie.MovieGenres = _listBox_details_genres.Items.Cast<string>().ToString(";");
            _movie.MovieOriginalTitle = _txt_details_origin.Text;
            _movie.MovieTagline = _txt_details_tagline.Text;
            _movie.MovieTitle = _txt_details_title.Text;
            _movie.MovieWriters = _txt_details_writer.Text;
            _movie.MovieYear = _txt_details_year.Text;
            #endregion

            MojHost.GetHost.MoJSystem.MoviesInterop.UpdateMovie(_movie);
            OnMovieInfoUpdated(this);
            MojHost.GetHost.AddToasts(string.Format("Movie {0}  was updated!", _txt_details_title.Text));
        }

        public event CallEventHandler OnMovieInfoUpdated;

        public bool Equals(IMetaData data)
        {
            return Identifier == data.Identifier;
        }
        #endregion

        private void ReleaseParent()
        {
            if (this.Parent != null)
            {
                try
                {
                    Panel p = this.Parent as Panel;
                    p.Children.Remove(this);
                    return;
                }
                catch { }
            }
            if (this.Parent != null)
            {
                try
                {
                    ContentControl c = this.Parent as ContentControl;
                    c.Content = null;
                    return;
                }
                catch { }
            }
        }
        private string BuildName(string Control)
        {
            return "blkx_MovieDetails_" + Control;
        }

        private void checkText(object sender, RoutedEventArgs e)
        {
            string _txt = ((TextBox)sender).Text;

            switch (((TextBox)sender).Name)
            {
                #region CheckTitleText
                case "_txt_details_title":
                    if (_txt.Length < 3)
                        _txt_details_title.Text = _movie.MovieTitle;

                    if (_movie.MovieTitle != _txt_details_title.Text)
                    {
                        _movie.MovieTitle = _txt_details_title.Text;
                        Save();
                    }
                    break;

                case "_txt_details_origin":
                    if (_movie.MovieOriginalTitle != _txt_details_origin.Text)
                    {
                        _movie.MovieOriginalTitle = _txt_details_origin.Text;
                        Save();
                    }
                    break;

                case "_txt_details_year":
                    if (!_txt.IsInt() || _txt.Length != 4)
                        _txt_details_year.Text = _movie.MovieYear;

                    if (_movie.MovieYear != _txt_details_year.Text)
                    {
                        _movie.MovieYear = _txt_details_year.Text;
                        Save();
                    }
                    break;

                case "_txt_details_tagline":
                    if (_movie.MovieTagline != _txt_details_tagline.Text)
                    {
                        _movie.MovieTagline = _txt_details_tagline.Text;
                        Save();
                    }
                    break;

                case "_txt_details_director":
                    if (_movie.MovieDirectors != _txt_details_director.Text)
                    {
                        _movie.MovieDirectors = _txt_details_director.Text;
                        Save();
                    }
                    break;

                case "_txt_details_writer":
                    if (_movie.MovieWriters != _txt_details_writer.Text)
                    {
                        _movie.MovieWriters = _txt_details_writer.Text;
                        Save();
                    }
                    break;
                #endregion
            }
        }

        private void SelectMovieIndex(object sender, RoutedEventArgs e)
        {
            if(_movie == null) return;
            int x = _listView_Files.SelectedIndex;
            if (x == -1) return;

            int n = _movieFiles.Count;
            if (n < 1)
                return;
            if (n == 1)
            {
                MojMovieFile file = _movieFiles[0];

                if (file.FileIndex == 1) return;

                file.FileIndex = 1;
                MojHost.GetHost.MoJSystem.FilesInterop.UpdateFile(file);
                ReloadMovie();
                return;
            }

            string[] opt = new string[n];
            for (int i = 0; i < n; i++)
                opt[i] = (i + 1).ToString();

            int res = MojHost.GetHost.SelectOptions(MOJLocalization.Localize(""), opt);
            res++;

            MojMovieFile f = _movieFiles[x];
            if (f.FileIndex == res) return;
            f.FileIndex = res;
            MojHost.GetHost.MoJSystem.FilesInterop.UpdateFile(f);
            ReloadMovie();
        }
        private void OnListViewMoviesSelectionChanged(object sender, RoutedEventArgs e)
        {
            int x = _listView_Files.SelectedIndex;

            _btn_files_remove.IsEnabled = x != -1;
            _btn_files_fileIndex.IsEnabled = x != -1;

            if (x == -1)
                MojStatusVarsEnum.SelectedFile.Set("NULL");
            else
                MojStatusVarsEnum.SelectedFile.Set(_movieFiles[x].FileID.ToString());
        }
        private void RemoveSelectedMovieFile(object sender, RoutedEventArgs e)
        {
            if (_movie == null) return;
            int x = _listView_Files.SelectedIndex;
            if (x == -1) return;

            string[] opt = { "Keep files", "Delete files", "Cancel" };
            int res = MojHost.GetHost.SelectOptions(MOJLocalization.Localize("Delete File"), opt);
            switch (res)
            {
                case 0:
                    MojHost.GetHost.MoJSystem.FilesInterop.RemoveFile(_movieFiles[x].FileID);
                    ReloadMovie();
                    return;

                case 1:
                    FileManageTools.AddToDelete(_movieFiles[x].FileFullPath);
                    MojHost.GetHost.MoJSystem.FilesInterop.RemoveFile(_movieFiles[x].FileID);
                    ReloadMovie();
                    return;

                case 2:
                    return;
            }
        }
        private void AddNewMovieFile(object sender, RoutedEventArgs e)
        {
            if (_movie == null) return;

            List<string> files = new List<string>(MojHost.GetHost.MoJSystem.TempFiles.FileCollection);
            int n = files.Count + 1;

            string[] opt = new string[n];
            opt[0] = MOJLocalization.Localize("Browse File");
            for (int i = 0; i < files.Count; i++)
            {
                opt[i + 1] = files[i];
            }

            int res = MojHost.GetHost.SelectOptions(MOJLocalization.Localize("Select File"), opt);
            if (res == 0)
            {

            }
            else
            {

            }
        }

        private void SelectSubtitleIndex(object sender, RoutedEventArgs e)
        {
            if (_movie == null) return;

            int n = _movie.SubtitleFiles.Count;
            string[] options = { "1", "2", "3" };
            int selected = MojHost.GetHost.SelectOptions("Select Subtitle Index", options);
            _btn_files_fileIndex.Content = selected.ToString();
        }
        private void SelectSubtitleLanguage(object sender, RoutedEventArgs e)
        {
            if (_movie == null) return;

            string[] opt = new Languages_ISO639_1().GetLanguages.ToArray();
            int i = MojHost.GetHost.SelectOptions("Select language", opt);
            _btn_subs_language.Content = opt[i];
        }

        private void FillDetails()
        {
            if (_movie == null) return;

            _txt_details_director.Text = _movie.MovieDirectors;
            _txt_details_origin.Text = _movie.MovieOriginalTitle;
            _txt_details_tagline.Text = _movie.MovieTagline;
            _txt_details_title.Text = _movie.MovieTitle;
            _txt_details_writer.Text = _movie.MovieWriters;
            _txt_details_year.Text = _movie.MovieYear;

            _listBox_details_cast.Items.Clear();
            foreach (var v in _movie.MovieCast.ToList(";"))
                _listBox_details_cast.Items.Add(v);

            _listBox_details_genres.Items.Clear();
            foreach (var v in _movie.MovieGenres.ToList(";"))
                _listBox_details_genres.Items.Add(v);
        }
        private void FillImages()
        {
            if (_movie == null) return;

            _img_imgs_Cover.Source = new BitmapImage(new Uri(_movie.CoverPath));
            _img_imgs_backdrop.Source = new BitmapImage(new Uri(_movie.BackdropPath));
        }
        private void FillMovies()
        {
            if(_movie == null) return;
            _Grid_Files.IsEnabled = _movie.MovieFiles.IsAvaible;

            _listView_Files.ItemsSource = null;
            _movieFiles = new ObservableCollection<MojMovieFile>(_movie.MovieFiles.OrderBy(z => z.FileIndex));
            _listView_Files.ItemsSource = _movieFiles;
        }
        private void FillSubtitles()
        {
            if (_movie == null) return;
            _Grid_Subtitles.IsEnabled = _movie.SubtitleFiles.IsAvaible;

            _listView_subtitles.ItemsSource = null;
            _subFiles = new ObservableCollection<MojSubtitleFile>(_movie.SubtitleFiles.OrderBy(z => z.FileIndex));
            _listView_subtitles.ItemsSource = _subFiles;
        }
    }
}
